using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace CSharpPro._1103
{
    public class UserService : IUserService
    {
        // 使用泛型集合存储用户信息
        private List<User> _registeredUsers = new List<User>();

        public void ShowMainMenu()
        {
            while (true)
            {
                Console.WriteLine("\n===== 主菜单 =====");
                Console.WriteLine("1. 登录");
                Console.WriteLine("2. 注册");
                Console.WriteLine("3. 退出");
                Console.Write("请选择功能(1-3): ");

                string input = Console.ReadLine()?.Trim();

                if (!int.TryParse(input, out int choice))
                {
                    Console.WriteLine("请输入有效数字(1-3)");
                    continue;
                }

                switch (choice)
                {
                    case 1:
                        Login();
                        break;
                    case 2:
                        Register();
                        break;
                    case 3:
                        Console.WriteLine("感谢使用，再见！");
                        return;
                    default:
                        Console.WriteLine("请输入有效数字(1-3)");
                        break;
                }
            }
        }

        public void Register()
        {
            Console.WriteLine("\n===== 用户注册 =====");

            // 获取并验证用户名
            string username;
            while (true)
            {
                Console.Write("请输入用户名: ");
                username = Console.ReadLine()?.Trim();

                if (string.IsNullOrEmpty(username))
                {
                    Console.WriteLine("用户名不可为空");
                    continue;
                }

                if (!IsValidUsername(username))
                {
                    Console.WriteLine("用户名格式错误，需3-15个字符，只能包含字母、数字和下划线");
                    continue;
                }

                // 使用foreach循环检查用户名是否已存在
                bool userExists = false;
                foreach (var user in _registeredUsers)
                {
                    if (user.Username == username)
                    {
                        userExists = true;
                        break;
                    }
                }

                if (userExists)
                {
                    Console.WriteLine("用户名已存在，请选择其他用户名");
                    continue;
                }

                break;
            }

            // 获取并验证密码
            string password;
            while (true)
            {
                Console.Write("请输入密码: ");
                password = ReadPassword();

                if (string.IsNullOrEmpty(password))
                {
                    Console.WriteLine("密码不可为空");
                    continue;
                }

                if (!IsValidPassword(password))
                {
                    Console.WriteLine("密码格式错误，需6-20个字符，且必须包含至少1个大写字母、1个小写字母和1个数字");
                    continue;
                }

                break;
            }

            // 验证确认密码
            while (true)
            {
                Console.Write("请确认密码: ");
                string confirmPassword = ReadPassword();

                if (string.IsNullOrEmpty(confirmPassword))
                {
                    Console.WriteLine("确认密码不可为空");
                    continue;
                }

                if (password != confirmPassword)
                {
                    Console.WriteLine("两次输入的密码不一致，请重新输入");
                    continue;
                }

                break;
            }

            // 注册成功，添加用户到泛型集合
            _registeredUsers.Add(new User(username, password));
            Console.WriteLine("注册成功！");
        }

        public void Login()
        {
            Console.WriteLine("\n===== 用户登录 =====");

            Console.Write("请输入用户名: ");
            string username = Console.ReadLine()?.Trim();

            if (string.IsNullOrEmpty(username))
            {
                Console.WriteLine("用户名不可为空");
                return;
            }

            Console.Write("请输入密码: ");
            string password = ReadPassword();

            if (string.IsNullOrEmpty(password))
            {
                Console.WriteLine("密码不可为空");
                return;
            }

            // 使用foreach循环验证用户信息
            bool loginSuccess = false;
            foreach (var user in _registeredUsers)
            {
                if (user.Username == username && user.Password == password)
                {
                    loginSuccess = true;
                    break;
                }
            }

            if (!loginSuccess)
            {
                // 检查用户名是否存在
                bool userExists = false;
                foreach (var user in _registeredUsers)
                {
                    if (user.Username == username)
                    {
                        userExists = true;
                        break;
                    }
                }

                if (!userExists)
                {
                    Console.WriteLine("登录失败：用户名不存在");
                }
                else
                {
                    Console.WriteLine("登录失败：密码错误");
                }
            }
            else
            {
                Console.WriteLine($"登录成功！欢迎回来，{username}！");
                ShowSystemHomepage(username);
            }
        }

        public void ShowSystemHomepage(string username)
        {
            Console.WriteLine("\n===== 系统首页 =====");
            Console.WriteLine($"当前用户：{username}");
            Console.WriteLine("这是系统首页，功能待扩展...");
            Console.WriteLine("按任意键返回主菜单...");
            Console.ReadKey();
        }

        public bool IsValidUsername(string username)
        {
            // 正则表达式：3-15个字符，只能包含字母、数字和下划线
            string pattern = @"^[a-zA-Z0-9_]{3,15}$";
            return Regex.IsMatch(username, pattern);
        }

        public bool IsValidPassword(string password)
        {
            // 检查长度
            if (password.Length < 6 || password.Length > 20)
                return false;

            // 检查是否包含至少1个大写字母、1个小写字母和1个数字
            bool hasUpper = false, hasLower = false, hasDigit = false;
            
            foreach (char c in password)
            {
                if (char.IsUpper(c)) hasUpper = true;
                else if (char.IsLower(c)) hasLower = true;
                else if (char.IsDigit(c)) hasDigit = true;

                // 如果所有条件都满足，提前退出循环
                if (hasUpper && hasLower && hasDigit)
                    break;
            }

            return hasUpper && hasLower && hasDigit;
        }

        public string ReadPassword()
        {
            string password = "";
            ConsoleKeyInfo key;

            do
            {
                key = Console.ReadKey(true);

                // 处理退格键
                if (key.Key == ConsoleKey.Backspace && password.Length > 0)
                {
                    password = password.Substring(0, password.Length - 1);
                    Console.Write("\b \b"); // 删除屏幕上的最后一个字符
                }
                // 处理除回车外的其他键
                else if (key.Key != ConsoleKey.Enter)
                {
                    password += key.KeyChar;
                    Console.Write("*"); // 显示星号代替输入的字符
                }
            } while (key.Key != ConsoleKey.Enter);

            Console.WriteLine(); // 换行
            return password;
        }
    }
}